import { ProjectConfig, AIProvider, ProjectInfo } from '../types';

/**
 * API服务基础URL
 */
const API_BASE_URL = 'http://localhost:3001/api';

/**
 * Git提交记录接口
 */
export interface GitCommit {
  hash: string;
  message: string;
  author: string;
  date: string;
  files: FileChange[];
}

/**
 * 文件变更接口
 */
export interface FileChange {
  file: string;
  type: 'added' | 'modified' | 'deleted';
  additions: number;
  deletions: number;
  diff?: string;
}

// ProjectInfo 类型已从 ../types 导入

/**
 * AI配置接口
 */
export interface AIConfig {
  provider: AIProvider;
  apiKey: string;
  model?: string;
  baseUrl?: string;
  temperature?: number;
  maxTokens?: number;
}

/**
 * API响应接口
 */
export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  error?: string;
}

/**
 * API客户端服务
 */
export class ApiService {
  /**
   * 发送HTTP请求
   */
  private static async request<T = any>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<ApiResponse<T>> {
    const url = `${API_BASE_URL}${endpoint}`;
    console.log(`[API] 请求: ${options.method || 'GET'} ${url}`);
    
    try {
      const response = await fetch(url, {
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
          ...options.headers,
        },
        ...options,
      });

      console.log(`[API] 响应: ${response.status} ${response.statusText}`);

      if (!response.ok) {
        const errorText = await response.text();
        console.error(`[API] 错误响应:`, errorText);
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log(`[API] 成功响应:`, data);
      return data;
    } catch (error) {
      console.error(`[API] 请求失败:`, error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '请求失败',
      };
    }
  }

  /**
   * 项目管理API
   */
  static projects = {
    /**
     * 获取所有项目
     */
    async getAll(): Promise<ApiResponse<ProjectInfo[]>> {
      const response = await ApiService.request('/git/projects');
      
      // 后端返回格式为 {success: true, data: Array}
      // 直接返回响应，无需转换
      return response as ApiResponse<ProjectInfo[]>;
    },

    /**
     * 添加项目
     */
    async add(name: string, path: string, description?: string): Promise<ApiResponse<ProjectInfo>> {
      return ApiService.request('/git/projects', {
        method: 'POST',
        body: JSON.stringify({ name, path, description }),
      }) as Promise<ApiResponse<ProjectInfo>>;
    },

    /**
     * 删除项目
     */
    async remove(id: string): Promise<ApiResponse<void>> {
      return ApiService.request(`/git/projects/${id}`, {
        method: 'DELETE',
      }) as Promise<ApiResponse<void>>;
    },

    /**
     * 获取项目作者列表
     */
    async getAuthors(projectPath: string): Promise<ApiResponse<string[]>> {
      // 确保projectPath是字符串类型
      if (typeof projectPath !== 'string') {
        console.error('[API] getAuthors - projectPath不是字符串类型:', typeof projectPath, projectPath);
        return {
          success: false,
          error: `无效的项目路径参数类型: ${typeof projectPath}`
        };
      }
      
      if (!projectPath.trim()) {
        console.error('[API] getAuthors - projectPath为空');
        return {
          success: false,
          error: '项目路径不能为空'
        };
      }
      
      console.log('[API] getAuthors - 使用的projectPath:', projectPath);
      const params = new URLSearchParams({ projectPath });
      return ApiService.request(`/git/projects/authors?${params}`) as Promise<ApiResponse<string[]>>;
    },

    /**
     * 获取项目总提交数
     */
    async getTotalCommits(projectPath: string): Promise<ApiResponse<number>> {
      // 确保projectPath是字符串类型
      if (typeof projectPath !== 'string') {
        console.error('[API] getTotalCommits - projectPath不是字符串类型:', typeof projectPath, projectPath);
        return {
          success: false,
          error: `无效的项目路径参数类型: ${typeof projectPath}`
        };
      }
      
      if (!projectPath.trim()) {
        console.error('[API] getTotalCommits - projectPath为空');
        return {
          success: false,
          error: '项目路径不能为空'
        };
      }
      
      console.log('[API] getTotalCommits - 使用的projectPath:', projectPath);
      const params = new URLSearchParams({ projectPath });
      return ApiService.request(`/git/projects/commits/count?${params}`) as Promise<ApiResponse<number>>;
    },
  };

  /**
   * Git数据API
   */
  static git = {
    /**
     * 获取Git提交记录
     */
    async getCommits(
      projectPath: string,
      options: {
        since?: string;
        until?: string;
        author?: string | string[];
        maxCount?: number;
        includeDiff?: boolean;
      } = {}
    ): Promise<ApiResponse<GitCommit[]>> {
      // 确保projectPath是字符串类型
      if (typeof projectPath !== 'string') {
        console.error('[API] getCommits - projectPath不是字符串类型:', typeof projectPath, projectPath);
        return {
          success: false,
          error: `无效的项目路径参数类型: ${typeof projectPath}`
        };
      }
      
      if (!projectPath.trim()) {
        console.error('[API] getCommits - projectPath为空');
        return {
          success: false,
          error: '项目路径不能为空'
        };
      }
      
      console.log('[API] getCommits - 使用的projectPath:', projectPath);
      const params = new URLSearchParams({
        projectPath,
        ...Object.fromEntries(
          Object.entries(options).filter(([_, value]) => value !== undefined)
        ),
      });
      
      const response = await ApiService.request(`/git/commits?${params}`);
      
      // 后端返回格式为 {success: true, commits: Array, total: number}
      // 需要转换为标准的 {success: true, data: Array} 格式
      if (response.success && (response as any).commits) {
        return {
          success: true,
          data: (response as any).commits
        };
      }
      
      return response as ApiResponse<GitCommit[]>;
    },

    /**
     * 根据提交哈希获取特定的提交记录
     */
    async getCommitsByHashes(
      projectPath: string,
      hashes: string[],
      includeDiff?: boolean
    ): Promise<ApiResponse<GitCommit[]>> {
      // 确保projectPath是字符串类型
      if (typeof projectPath !== 'string') {
        console.error('[API] getCommitsByHashes - projectPath不是字符串类型:', typeof projectPath, projectPath);
        return {
          success: false,
          error: `无效的项目路径参数类型: ${typeof projectPath}`
        };
      }
      
      if (!projectPath.trim()) {
        console.error('[API] getCommitsByHashes - projectPath为空');
        return {
          success: false,
          error: '项目路径不能为空'
        };
      }
      
      console.log('[API] getCommitsByHashes - 使用的projectPath:', projectPath);
      
      const response = await ApiService.request('/git/commits/by-hashes', {
        method: 'POST',
        body: JSON.stringify({
          projectPath,
          hashes,
          includeDiff: includeDiff?.toString()
        })
      });
      
      // 后端返回格式为 {success: true, commits: Array}
      // 需要转换为标准的 {success: true, data: Array} 格式
      if (response.success && (response as any).commits) {
        return {
          success: true,
          data: (response as any).commits
        };
      }
      
      return response as ApiResponse<GitCommit[]>;
    },

    /**
     * 获取Git仓库信息
     */
    async getRepoInfo(projectPath: string): Promise<ApiResponse<{
      branch: string;
      remoteUrl: string;
      isGitRepo: boolean;
    }>> {
      // 确保projectPath是字符串类型
      if (typeof projectPath !== 'string') {
        console.error('[API] getRepoInfo - projectPath不是字符串类型:', typeof projectPath, projectPath);
        return {
          success: false,
          error: `无效的项目路径参数类型: ${typeof projectPath}`
        };
      }
      
      if (!projectPath.trim()) {
        console.error('[API] getRepoInfo - projectPath为空');
        return {
          success: false,
          error: '项目路径不能为空'
        };
      }
      
      console.log('[API] getRepoInfo - 使用的projectPath:', projectPath);
      const params = new URLSearchParams({ projectPath });
      return ApiService.request(`/git/info?${params}`) as Promise<ApiResponse<{
        branch: string;
        remoteUrl: string;
        isGitRepo: boolean;
      }>>;
    },
  };

  /**
   * AI报告生成API
   */
  static ai = {
    /**
     * 生成报告
     */
    async generateReport(
      commits: GitCommit[],
      template: string,
      config: AIConfig
    ): Promise<ApiResponse<{ content: string }>> {
      return ApiService.request('/ai/reports/generate', {
        method: 'POST',
        body: JSON.stringify({
          commits,
          template,
          config,
        }),
      }) as Promise<ApiResponse<{ content: string }>>;
    },

    /**
     * AI代理请求
     */
    async proxy(
      url: string,
      options: {
        method?: string;
        headers?: Record<string, string>;
        body?: any;
      }
    ): Promise<ApiResponse<any>> {
      return ApiService.request('/ai/proxy', {
        method: 'POST',
        body: JSON.stringify({ url, ...options }),
      }) as Promise<ApiResponse<any>>;
    },
  };

  /**
   * 健康检查
   */
  static async healthCheck(): Promise<ApiResponse<{ status: string; timestamp: string }>> {
    return ApiService.request('/health') as Promise<ApiResponse<{ status: string; timestamp: string }>>;
  }
}

// 默认导出
export default ApiService;